import { ref } from 'vue'

// 购物车数据
const cartItems = ref([])

// 添加菜品到购物车
export const addToCart = (recipe) => {
  const existingItem = cartItems.value.find(item => item.id === recipe.id)
  if (existingItem) {
    existingItem.quantity += 1
  } else {
    cartItems.value.push({
      ...recipe,
      quantity: 1
    })
  }
}

// 从购物车移除菜品
export const removeFromCart = (recipeId) => {
  const index = cartItems.value.findIndex(item => item.id === recipeId)
  if (index > -1) {
    cartItems.value.splice(index, 1)
  }
}

// 更新菜品数量
export const updateQuantity = (recipeId, quantity) => {
  const item = cartItems.value.find(item => item.id === recipeId)
  if (item) {
    item.quantity = quantity
  }
}

// 获取购物车总价
export const getTotalPrice = () => {
  return cartItems.value.reduce((total, item) => {
    return total + (item.price || 0) * item.quantity
  }, 0)
}

// 获取购物车总数量
export const getTotalQuantity = () => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
}

// 清空购物车
export const clearCart = () => {
  cartItems.value = []
}

export const useCart = () => {
  return {
    cartItems,
    addToCart,
    removeFromCart,
    updateQuantity,
    getTotalPrice,
    getTotalQuantity,
    clearCart
  }
} 